/*
 * Copyright 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.superme.bizclientbyribbon.controller;



import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.*;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

import org.slf4j.Logger;



@RestController
public class BizserverHomeController {

	private static final Logger LOGGER = LoggerFactory.getLogger(BizserverHomeController.class);

	@Autowired
	//private OAuth2RestTemplate template;
	private OAuth2RestTemplate otemplate;

	@Autowired
	private LoadBalancerClient loadBalancerClient;


	//从zuul调用
	@RequestMapping(value = "/test",method = RequestMethod.GET)
	@ResponseBody
	public String test(OAuth2Authentication oAuth2Authentication) {
		if(oAuth2Authentication !=null) {
			//String url = "http://resoucesserver:8870/dummy/";
			String url = "http://gatewayserver:8765/res/";
			HttpHeaders headers = new HttpHeaders();
			//headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			//headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
			//OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)principal.getDetails();
			//String tokenValue = details.getTokenValue();
			//headers.add("Authorization", String.format("%s %s", "Bearer", tokenValue));
			HttpEntity entity =  new HttpEntity<String>(headers);

			HashMap<String,String> maps = new HashMap<String,String>();
			//maps.put("access_token",tokenValue);
			ResponseEntity<String> response = otemplate.exchange(url,HttpMethod.GET,entity, String.class, maps);
			return  response.getBody();
		}
		else {
			return "anonymous";
		}
	}


}
